package com.wlyuan.open.scanner.application.handler.incr;

import com.wlyuan.open.dto.OpenOrderSyncDTO;
import com.wlyuan.open.scanner.application.async.AsyncOrderThreadUtils;
import com.wlyuan.open.scanner.application.task.order.OrderTaskHandler;
import com.wlyuan.open.scanner.assembler.ScannerOrderAssembler;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.constant.ScannerCodeEnum;
import com.wlyuan.open.scanner.repository.OrderRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Optional;
import java.util.concurrent.CountDownLatch;

/**
 * @author lijing
 * @description 订单 增量listener
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderIncrHandler extends BaseIncrHandler<OpenOrderSyncDTO> {
    private final OrderRepository orderRepository;
    private final OrderTaskHandler orderTaskHandler;

    @Override
    public OpenOrderSyncDTO process(Long orderId) {
        logger.info("订单增量同步：{}", orderId);
        return Optional.ofNullable(orderId).map(id -> {
            var order = orderRepository.getById(id);
            return ScannerOrderAssembler.assemble(order);
        }).orElse(null);
    }

    @Override
    public void incrByTenantId(Long tenantId) {
        orderTaskHandler.handler(tenantId);
    }

    @Override
    public void incrByTime(Long tenantId, String startTime, String endTime) {
        var list = tenantId == null ? orderRepository.getOrderIdByTime(startTime, endTime) : orderRepository.getOrderIdByTenantIdTime(tenantId, startTime, endTime);
        if (CollectionUtils.isEmpty(list)) {
            logger.info("根据时间{},{}数据为0", startTime, endTime);
            return;
        }
        logger.info("根据时间{},{}数据为：{}", startTime, endTime, list.size());
        var partitionList = ListUtils.partition(list, Constants.PAGE_SIZE);
        CountDownLatch countDownLatch = new CountDownLatch(partitionList.size());
        partitionList.parallelStream().forEach(partition -> {
            AsyncOrderThreadUtils.getInstance().excute(new Thread(() -> {
                partition.parallelStream().forEach(id -> increment(id));
                countDownLatch.countDown();
            }));
        });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {

        }
        logger.info("同步完成");
    }

    @Override
    public String getSyncType() {
        return ScannerCodeEnum.ORDER.getVal();
    }

}
